/*
 * Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following
 * conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 *  * Neither the name of the The National Archives nor the
 *    names of its contributors may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package uk.gov.nationalarchives.droid.gui.filter;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.swing.BorderFactory;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import uk.gov.nationalarchives.droid.gui.filter.domain.FilterValidationException;

/**
 * @author Alok Kumar Dash
 */
public class DatePicker extends javax.swing.JPanel {

    /** */
    private static final String INVALID_DATE = "Invalid date";
    private static final int MONTH_END_INDEX = 5;
    private static final int MONTH_START_INDEX = 3;

    private static final long serialVersionUID = -4884183026736825056L;

    private static final String DATE_DELIMITER = "/";

    private final Logger log = LoggerFactory.getLogger(getClass());
    
    /** 
     * Creates new DatePicker component.
     */
    public DatePicker() {
        initComponents();
        
        GregorianCalendar cal = new GregorianCalendar();
        int minDay = cal.getMinimum(Calendar.DAY_OF_MONTH);
        int maxDay = cal.getMaximum(Calendar.DAY_OF_MONTH);
        int minMonth = cal.getMinimum(Calendar.MONTH);
        int maxMonth = cal.getMaximum(Calendar.MONTH);
        
        List<Integer> days = new ArrayList<Integer>();
        List<Integer> months = new ArrayList<Integer>();
        for (int i = minDay; i <= maxDay; i++) {
            days.add(i);
        }
        for (int i = minMonth; i <= maxMonth; i++) {
            months.add(i + 1);
        }
        
        dayComboBox.setModel(new javax.swing.DefaultComboBoxModel(days.toArray()));
        monthComboBox.setModel(new javax.swing.DefaultComboBoxModel(months.toArray()));

        jLabel1.setText("Day:"); 

        jLabel2.setText("Month:"); 

        jLabel3.setText("Year:"); 
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dayComboBox = new javax.swing.JComboBox();
        monthComboBox = new javax.swing.JComboBox();
        yearTextBox = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        dayComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        monthComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        yearTextBox.setText(org.openide.util.NbBundle.getMessage(DatePicker.class, "DatePicker.yearTextBox.text")); // NOI18N

        jLabel1.setText(org.openide.util.NbBundle.getMessage(DatePicker.class, "DatePicker.jLabel1.text")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(DatePicker.class, "DatePicker.jLabel2.text")); // NOI18N

        jLabel3.setText(org.openide.util.NbBundle.getMessage(DatePicker.class, "DatePicker.jLabel3.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(dayComboBox,
                        javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(15, 15, 15)
                .addComponent(jLabel2)
                .addGap(12, 12, 12)
                .addComponent(monthComboBox,
                        javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(yearTextBox, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(dayComboBox,
                        javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1)
                .addComponent(jLabel2)
                .addComponent(jLabel3)
                .addComponent(monthComboBox,
                        javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(yearTextBox,
                        javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * FIXME: javadoc.
     */
    public void setRedBorderToYearBox() {
        yearTextBox.setBorder(BorderFactory.createLineBorder(Color.red));
        repaint();
    }

    /**
     * FIXME: javadoc.
     */
    public void clearRedBorderToYearBox() {
        yearTextBox.setBorder(null);
        repaint();
    }


    /**
     * FIXME: javadoc.
     */
    public void setRedBorderToMonthBox() {
        monthComboBox.setBorder(BorderFactory.createLineBorder(Color.red));
        repaint();
    }

    /**
     * FIXME: javadoc.
     */
    public void clearRedBorderToMonthBox() {
        monthComboBox.setBorder(null);
        repaint();
    }


    /**
     * FIXME: javadoc.
     */
    public void setRedBorderToDayBox() {
        dayComboBox.setBorder(BorderFactory.createLineBorder(Color.red));
        repaint();
    }

    /**
     * FIXME: javadoc.
     */
    public void clearRedBorderToDayBox() {
        dayComboBox.setBorder(null);
        repaint();
    }
    
    
    /**
     * FIXME: javadoc.
     */
    public void paintRedBoxToComponents() {
        yearTextBox.setBorder(BorderFactory.createLineBorder(Color.red));
        monthComboBox.setBorder(BorderFactory.createLineBorder(Color.red));
        dayComboBox.setBorder(BorderFactory.createLineBorder(Color.red));
        repaint();
    }
    
    /**
     * FIXME: javadoc.
     */
    public void clearRedBoxToComponents() {
        yearTextBox.setBorder(null);
        monthComboBox.setBorder(null);
        dayComboBox.setBorder(BorderFactory.createLineBorder(Color.red));
        repaint();
    }
    

    /**
     * FIXME: javadoc.
     * @return FIXME: javadoc
     * @throws FilterValidationException if the date entered was not valid.
     */
    public String getDateString() throws FilterValidationException {
        
        try {
            DateMidnight date = new DateMidnight(
                    Integer.valueOf(yearTextBox.getText()),
                    (Integer) monthComboBox.getSelectedItem(),
                    (Integer) dayComboBox.getSelectedItem());
            
            return ISODateTimeFormat.date().print(date);
        } catch (IllegalFieldValueException e) {
            throw new FilterValidationException(INVALID_DATE);
        } catch (NumberFormatException e) {
            throw new FilterValidationException(INVALID_DATE);
        }
    }
    
    
    /**
     * FIXME: javadoc.
     * @param contextDate FIXME: javadoc
     */
    public void setDateCombos(String contextDate) {
        DateTime date = ISODateTimeFormat.date().parseDateTime(contextDate);
        dayComboBox.getModel().setSelectedItem(date.getDayOfMonth());
        monthComboBox.getModel().setSelectedItem(date.getMonthOfYear());
        yearTextBox.setText(String.valueOf(date.getYear()));
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox dayComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JComboBox monthComboBox;
    private javax.swing.JTextField yearTextBox;
    // End of variables declaration//GEN-END:variables

}
